package com.alexgaoyh.weixin.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alexgaoyh.weixin.core.CoreService;
import com.alexgaoyh.weixin.servlet.digest.WeixinMessageDigest;


/**
 * 核心请求处理类 
 * @author alexgaoyh
 *
 */
@SuppressWarnings("serial")
public class WechatCallbackApi extends HttpServlet {
    // 自定义 token
    private String TOKEN = "alexgaoyh";
    
    /** 
     * 确认请求来自微信服务器 
     * 进行微信公共平台 服务器配置 token校验相关流程时使用的
     */  
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");

        WeixinMessageDigest wxDigest = WeixinMessageDigest.getInstance(); 
        
        boolean isValidated = wxDigest.validate(signature, timestamp, nonce, TOKEN);     

        // 确认请求来至微信
        if (isValidated) {
            response.getWriter().print(echostr);
        }
    }
    
    /** 
     * 处理微信服务器发来的消息 
     * 是核心业务不在此servlet中执行，将这一部分流程转移到核心服务类中处理
     */  
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    		throws ServletException, IOException {
    	
    	// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
    	req.setCharacterEncoding("UTF-8");  
    	resp.setCharacterEncoding("UTF-8");  
    	
        // 调用核心业务类接收消息、处理消息  
        String respMessage = CoreService.processRequest(req);  
          
        // 响应消息  
        PrintWriter out = resp.getWriter();  
        out.print(respMessage);  
        out.close();  
    }
    
}